package com.ithinks.flow.common.utils.middleware.rabbitMQ.workQueue;

import com.ithinks.flow.common.utils.middleware.rabbitMQ.ConnectionUtils;
import com.rabbitmq.client.*;
import net.sf.json.JSONObject;

import java.io.IOException;

/**
 * @Description
 * @ClassName WorkQueneConsumer
 * @Author MR.LI
 * @date 2020.11.26 18:15
 */
public class WorkQueneConsumer {

    private final static String QUEUE_NAME = "register";

    private static String IP = "localhost";
    //端口
    private static int PORT = 5672;
    //虚拟机IP，默认/
    private static String VHOST = "/";
    //队列名称
    private static String USERNAME = "guest";

    private static String PASSWORD = "guest";

    public static void main(String[] args) throws IOException {

        Connection connection = ConnectionUtils.getConnection(IP,PORT,VHOST,USERNAME,PASSWORD);
        final Channel channel = connection.createChannel();
        Consumer consumer = null;
        try {
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);;
            //每次从队列中获取数量
            channel.basicQos(1);
            consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);
                    String message = new String(body,"UTF-8");
                    JSONObject jsonObject = JSONObject.fromObject(message);
                    String msgType = jsonObject.get("msgType").toString();
                    System.out.println("worker1 Received msgType"+msgType);
                    if(msgType.equals("email"))
                    {
                        System.out.println("worker1 do "+jsonObject.get("content"));
                    }else
                    {
                        System.out.println("worker1 do "+jsonObject.get("content"));
                    }
                    System.out.println("Worker1 Done");
                    //注意这句为必须，否则会造成RabbitMQ因为重复的重新发送已处理的消息而内存溢出
                    channel.basicAck(envelope.getDeliveryTag(),false);

                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        channel.basicConsume(QUEUE_NAME,false,consumer);

    }
}
